package com.example.lib5.hashTab.test;

public class HashTabDemo {
    public static void main(String[] args) {
        RoleHashTab roleHashTab = new RoleHashTab(7);
        roleHashTab.add(new Role(111,"唐三","昊天宗"));
        roleHashTab.add(new Role(112,"小舞","十万年魂兽"));
        roleHashTab.add(new Role(113,"千仞雪","武魂殿"));
        roleHashTab.list();
    }

}

//节点
class Role {
    int id;
    String name;
    String bg;
    Role next;

    public Role(int id, String name, String bg) {
        this.id = id;
        this.name = name;
        this.bg = bg;
    }

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", bg='" + bg + '\'' +
                '}';
    }
}

//链表
class LinkListRole {
    private Role head;

    //增加
    public void add(Role role) {
        //如果链表为空，就直接加入即可
        if (head == null) {
            head = role;
            return;
        }
        Role temp = head;
        //不为空，就遍历到最后一个节点，然后添加进去
        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = role;

    }

    //遍历
    public void list(int i) {
        if (head == null) {
            System.out.println("第"+i+"链表为空");
            return;
        }
        Role temp = head;
        while (true) {
            System.out.println("第"+i+"链表："+temp.toString());
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
    }


}
//哈希表
class RoleHashTab {
    private final int size;
    LinkListRole[] linkListRoles;
    public RoleHashTab(int size) {
        linkListRoles=new LinkListRole[size];
        for (int i = 0; i < linkListRoles.length; i++) {
            linkListRoles[i]=new LinkListRole();
        }
        this.size=size;

    }

    public void add(Role role) {
        linkListRoles[getHash(role.id)].add(role);
    }

    private int getHash(int id) {
        return id%10;
    }

    public void list() {
        for (int i = 0; i < linkListRoles.length; i++) {
            linkListRoles[i].list(i);
        }
    }
}